<template>
    <div class="list-box">
        <div class="pannel-title pannel-between">
            <div>文章分类列表</div>
        </div>
        <div class="line"></div>
		<div class="pannel-tabs">
			<router-link :to="{path:'/articleType',query:{type:'Tech'}}" :class="{active:active === 'Tech'}">技术文章分类</router-link>
			<router-link :to="{path:'/articleType',query:{type:'Vuln'}}" :class="{active:active === 'Vuln'}">漏洞文章分类</router-link>
			<a-button type="primary" class="right-btn" @click="createArticleType">+ 新增文章分类</a-button>
		</div>
        <div class="data-table">
            <a-table
				v-show="active === 'Tech'"
                :columns="columns"
                :row-key="(record) => record.id"
                :data-source="dataSource1"
                :pagination="false"
                :loading="isLoading"
            >
                <template #action="{record}">
                    <a v-if="record.pid === 0" @click="addChildMenu(record)" title="新增子分类" style="margin-right:5px;"><img src="@/assets/images/cz-add.png"/></a>
                    <a @click="editMenu(record)" title="编辑" style="margin-right:5px;"><img src="@/assets/images/cz-edit.png"/></a>
                    <a @click="deleteMenu(record)" title="删除"><img src="@/assets/images/cz-delete.png"/></a>
                </template>
            </a-table>
            <a-table
				v-show="active === 'Vuln'"
                :columns="columns"
                :row-key="(record) => record.id"
                :data-source="dataSource2"
                :pagination="false"
                :loading="isLoading"
            >
                <template #action="{record}">
                    <a v-if="record.pid === 0" @click="addChildMenu(record)" title="新增子分类" style="margin-right:5px;"><img src="@/assets/images/cz-add.png"/></a>
                    <a @click="editMenu(record)" title="编辑" style="margin-right:5px;"><img src="@/assets/images/cz-edit.png"/></a>
                    <a @click="deleteMenu(record)" title="删除"><img src="@/assets/images/cz-delete.png"/></a>
                </template>
            </a-table>
            <a-modal v-model:visible="visible" :maskClosable="false" :afterClose="closeModal">
                <h3 class="modal-title">{{ modalTitle }}</h3>
                <div class="modal-form">
                    <a-form ref="form1" :model="formState" :rules="rules" :labelCol="{span:6,offset:0}">
                        <a-form-item label="分类名称" name="name">
                            <a-input
                                v-model:value="formState.name"
                                placeholder="请输入分类名称"
                            />
                        </a-form-item>
                        <a-form-item label="排序序号" name="displayPriority">
							<a-input v-model:value="formState.displayPriority" placeholder="请输入大于等于0的正整数">
								<template #suffix>
									<a-tooltip title="排序序号数值越小越靠前">
										<info-circle-outlined style="color: rgba(255, 0, 0, 0.7)" />
									</a-tooltip>
								</template>
							</a-input>
						</a-form-item>
                    </a-form>
                </div>
                <template #footer>
                    <div class="modal-btn">
                        <a-button type="default" shape="round" @click="closeModal">取消</a-button>
                        <a-button :loading="btnLoading" type="primary" shape="round" @click="confirm()">确定</a-button>
                    </div>
                </template>
            </a-modal>
        </div>
    </div>
</template>
<script>
import { InfoCircleOutlined } from "@ant-design/icons-vue";
import { useStore } from "vuex";
import { reactive, ref } from "@vue/reactivity";
import { message, Table, Modal,Button,Form,Input,Tooltip} from "ant-design-vue";
import httpRequest from "@/util/httpRequest";
export default {
    components: {
        ATable: Table,
		AModal:Modal,
		AButton:Button,
		AForm:Form,
		AFormItem:Form.Item,
		AInput:Input,
		ATooltip:Tooltip,
		InfoCircleOutlined
    },
    setup() {
        const store = useStore();
        //text：页面头部面包屑的显示文字，isBack：是否显示页面头部返回按钮
        store.dispatch("setBreadcrumb", {
            text: "系统设置 / 菜单管理",
            isBack: false,
        });
        const dataSource1 = ref([]);
        const dataSource2 = ref([]);
        const columns = reactive([
            {
                title: "分类名称",
                dataIndex: "name",
                key: "name",
            },
            {
                title: "排序序号",
                dataIndex: "display_priority",
                key: "display_priority",
            },
            {
                title: "创建日期",
                dataIndex: "create_time",
                key: "create_time",
            },
            {
                title: "操作",
                key: "action",
                slots: { customRender: "action" },
            },
        ]);
        return {
            dataSource1,
            dataSource2,
            columns,
			TechList:ref([]),
			VulnList:ref([]),
            isLoading: ref(false),
            visible: ref(false),
			modalTitle:ref(''),
			btnLoading:ref(false)
        };
    },
    data() {
        return {
			formState:{
				id:'',
				pid:'',
				name:'',
				type:'',
				displayPriority:'',
			},
            rules: {
                name:{
					required: true,
					message: "不能为空",
					trigger: "blur",
				},
				displayPriority: [
					{
						required: true,
						message: "不能为空",
						trigger: "blur",
					},
					{
						trigger: "blur",
						message: "请输入大于等于0的整数",
						pattern: /^(0|[1-9]\d*)$/,
					},
				],
            },
			active:'Tech',
			
        };
    },
    mounted() {
		if(this.$route.query.type){
			this.active = this.$route.query.type;
		}
        this.getList();
    },
	updated(){
		if(this.$route.query.type){
			this.active = this.$route.query.type;
		}
	},
    methods: {
        getList() {
            this.isLoading = true;
            httpRequest
                .post("获取文章分类列表", {})
                .then((res) => {
					this.TechList = res.data.filter(e=>e.type==='Tech');
					this.VulnList = res.data.filter(e=>e.type==='Vuln');
                    this.dataSource1 = this.getMenuByTree(this.TechList);
                    this.dataSource2 = this.getMenuByTree(this.VulnList);
                })
                .finally(() => {
                    this.isLoading = false;
                });
        },
		getMenuByTree(list){
			const array = list.filter(e=>e.pid === 0);
			const obj = {};
			list.forEach(e=>{
				obj[e.id] = e;
			});
			list.forEach(e=>{
				if(e.pid !== 0){
					if(obj[e.pid].children){
						obj[e.pid].children.push(e);
					}else{
						obj[e.pid].children=[e];
					}
				}
			});
			return array;
		},
        deleteMenu(item) {
            Modal.confirm({
                title: "系统提示",
                content: "确认删除当前文章分类？",
                okText: "确认",
                cancelText: "取消",
                onOk: () => {
                    return new Promise((res) => {
                        httpRequest
                            .post("删除文章分类", { id: item.id })
                            .then(() => {
                                message.success("文章分类删除成功！");
                                this.getList();
                            })
                            .catch(() => {
                                message.warning({ content: "文章分类删除失败", key: "error" });
                            })
                            .finally(() => {
                                this.isLoading = false;
                                res();
                            });
                    });
                },
            });
        },
        editMenu(item) {
			if(this.$refs.form1&&this.$refs.form1.resetFields){
				this.$refs.form1.resetFields();
			}
			this.formState = {
				id:item.id,
				pid:item.pid,
				type:item.type,
				name:item.name,
				displayPriority:String(item.display_priority),
			};
			this.modalTitle = "编辑文章分类";
            this.visible = true;
        },
        createArticleType() {
			if(this.$refs.form1&&this.$refs.form1.resetFields){
				this.$refs.form1.resetFields();
			}
			this.formState = {
				id:"",
				pid:0,
				name:"",
				displayPriority:"",
				type:this.active
			}
			this.modalTitle = this.active === 'Tech' ? "新增技术文章分类":"新增漏洞文章分类";
            this.visible = true;
        },
		addChildMenu(item){
			if(this.$refs.form1&&this.$refs.form1.resetFields){
				this.$refs.form1.resetFields();
			}
			this.formState = {
				id:"",
				pid:item.id,
				name:"",
				displayPriority:"",
				type:this.active
			};
			this.modalTitle ="新增子分类";
			this.visible = true;
		},
        confirm() {
            this.$refs.form1.validate().then(()=>{
                const url = this.formState.id ? "编辑文章分类" : "创建文章分类";
                const msg = this.formState.id ? "修改成功" : "创建成功";
				this.btnLoading = true;
                httpRequest.post(url, this.formState).then(() => {
                    this.visible = false;
					this.getList();
                    message.success(msg);
                }).finally(()=>{
					this.btnLoading = false;
				});
            })
 
        },
		closeModal(){
			this.visible = false;
		}
    },
};
</script>
<style lang="less" scoped>
.line {
    width: 100%;
    margin: 20px 0;
    border-top: 1px solid #eee;
}
.pannel-tabs{
	height: 40px;
	line-height: 39px;
	border-bottom: 1px solid #f1f1f1;
	text-align: left;
	margin-bottom: 10px;
	a{
		color: #666;
		display: inline-block;
		height: 40px;
		border:1px solid #f1f1f1;
		background: #f8f8f8;
		border-bottom: 1px solid transparent;
		padding:0 15px;
		border-radius: 4px 4px 0 0;
		margin-right: 3px;
		&:hover{
			color: #378EF0;
		}
		&.active{
			color: #378EF0;
			background: #fff;
			border-bottom-color: #fff;
		}
	}
	.right-btn{
		float: right;
	}
}
</style>
